﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MoneyController
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int UNKNOWN_CATEGORY_ID = -1;
        readonly BankbookDBEntities bankbookDBEntities = new BankbookDBEntities();
        List<Button> categoryButtons = new List<Button>();

        public MainWindow()
        {
            InitializeComponent();

            textBox1.Text =
                @"2012-06-29	 	2012-06-28	 	MAXI ICA STORM	 	-149,00	 	20 206,43
2012-06-29	 	2012-06-28	 	GUNSAV HB	 	-145,00	 	20 355,43
2012-06-29	 	2012-06-28	 	CURA APOTEK GO	 	-185,00	 	20 500,43
2012-06-29	 	2012-06-28	 	MAXI ICA STORM	 	-1 357,45	 	20 685,43
2012-06-29	 	2012-06-29	 	DR LINDH BRF	 	-4 517,00	 	22 042,88
2012-06-29	 	2012-06-29	 	Dyröns Idrotts	 	-200,00	 	26 559,88
2012-06-29	 	2012-06-29	 	AVANZA BANK	 	-400,00	 	26 759,88
2012-06-28	 	2012-06-28	 	Mat mm juni	 	-2 700,00	 	27 159,88";

            categoryButtons.Add(button1);
            categoryButtons.Add(button2);
            categoryButtons.Add(button3);
            categoryButtons.Add(button4);
            categoryButtons.Add(button5);
            categoryButtons.Add(button6);
            categoryButtons.Add(button7);
            categoryButtons.Add(button8);
            categoryButtons.Add(button9);
            categoryButtons.Add(button10);
            categoryButtons.Add(button11);
            categoryButtons.Add(button12);
            categoryButtons.Add(button13);
            categoryButtons.Add(button14);
            categoryButtons.Add(button15);
            categoryButtons.Add(button16);
            categoryButtons.Add(button17);
            categoryButtons.Add(button18);
            categoryButtons.Add(button19);
            categoryButtons.Add(button20);

            SetUpCategoryButtons();

            datePickerFrom.SelectedDate = DateTime.Now.AddMonths(-2);
            datePickerTo.SelectedDate = DateTime.Now;
            //ShowNextTextToSetCategoryOn();
        }

        private void SetUpCategoryButtons()
        {
            // Clear all buttons first
            foreach (Button button in categoryButtons)
            {
                button.IsEnabled = false;
                button.Click -= SetCategoryButtonClicked;
            }

            // Get uniqe categories from existing bankbook
            int buttonIndex = 0;
            var uniqueCategoryTexts =
                bankbookDBEntities.BankBook.Where(b => b.Category != null).Select(b => b.Category).Distinct().ToList();

            // Add categories to buttons
            foreach (var category in uniqueCategoryTexts)
            {
                categoryButtons[buttonIndex].Content = category;
                categoryButtons[buttonIndex].Tag = category;
                categoryButtons[buttonIndex].IsEnabled = true;
                categoryButtons[buttonIndex].Click += SetCategoryButtonClicked;
                buttonIndex++;

            }

            //foreach (Button button in categoryButtons)
            //{
            //    if (button.Tag != null)
            //        continue;

            //    button.IsEnabled = false;
            //    button.Click -= SetCategoryButtonClicked;
            //}
        }

        private void buttonParse_Click(object sender, RoutedEventArgs e)
        {
            string text = textBox1.Text;
            string[] splitter = new string[] {"\r\n"};
            string[] rows = text.Split(splitter, Int32.MaxValue, StringSplitOptions.None);

            var currentBankbooks = bankbookDBEntities.BankBook.ToList();

            foreach (var row in rows)
            {
                //string[] splitTab = new string[] { "\t" };
                char[] splitTab = new char[] {'\t'};


                string[] parsedFields = row.Split(splitTab, Int32.MaxValue, StringSplitOptions.RemoveEmptyEntries);
                List<string> fields = new List<string>();
                foreach (var fieldString in parsedFields)
                {
                    if (fieldString.Trim() == "")
                        continue;
                    
                    fields.Add(fieldString.Trim());
                }

                if (fields.Count < 4)
                    continue;

                DateTime bankbookDate = Convert.ToDateTime(fields[1]);
                string bankbookText = fields[2];
                double bankbookSEK = Convert.ToDouble(fields[3]);

                if (DoesBankbookPostAlreadyExisit(bankbookDate, bankbookText, bankbookSEK))
                    continue;

                BankBook newPost = new BankBook();
                newPost.Id = GetNextBankBookID();
                newPost.Date = bankbookDate;
                newPost.Text = bankbookText;
                newPost.SEK = bankbookSEK;
                
                bankbookDBEntities.AddToBankBook(newPost);
            }

            bankbookDBEntities.SaveChanges();

        }

        private bool DoesBankbookPostAlreadyExisit(DateTime dateTime, string text, double sek)
        {
            return bankbookDBEntities.BankBook.Where(bb => bb.Date == dateTime && bb.Text == text && bb.SEK == sek).FirstOrDefault() !=
                   null;
        }

        private int GetNextBankBookID()
        {
            var bankbookIncludingNewObject =
                bankbookDBEntities.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified |
                                                                            EntityState.Unchanged).Select(o => o.Entity)
                    .OfType<BankBook>();

            var oo = bankbookIncludingNewObject.Count();
            if (bankbookDBEntities.BankBook.Count() == 0)
                return 1;

            var currentMax = bankbookIncludingNewObject.Max(b => b.Id);

            
            return currentMax + 1;
        }

        private void buttonNewCategory_Click(object sender, RoutedEventArgs e)
        {
            string text = textboxNewCategory.Text.Trim();
            if (text == "")
                return;

            SetCategoryOnSelectedRow(text);

            //Category newCategory = new Category();
            //newCategory.CategoryId = GetNextCategoryId();
            //newCategory.Name = text;
            //bankbookDBEntities.Category.AddObject(newCategory);

            //bankbookDBEntities.SaveChanges();

            SetUpCategoryButtons();
        }

        //private int GetNextCategoryId()
        //{
        //    if (bankbookDBEntities.Category.Count() == 0)
        //        return 1;

        //    return bankbookDBEntities.Category.Count() + 1;
        //}

        private void SetCategoryOnSelectedRow(string category)
        {
            BankBook selectedBankBook = (BankBook)dataGridBankbook.SelectedItem;
            if (selectedBankBook == null)
                return;
            
            selectedBankBook.Category = category;

            bankbookDBEntities.SaveChanges();
            ShowBankbook();

        }

        private void SetCategoryButtonClicked(object sender, RoutedEventArgs e)
        {
            string category = (string)((Button)sender).Tag;
            SetCategoryOnSelectedRow(category);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ShowBankbook();
            //MoneyController.BankbookDBEntities bankbookDBEntities = new MoneyController.BankbookDBEntities();
            //// Load data into BankBook. You can modify this code as needed.
            //System.Windows.Data.CollectionViewSource bankBookViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("bankBookViewSource")));
            //System.Data.Objects.ObjectQuery<MoneyController.BankBook> bankBookQuery = this.GetBankBookQuery(bankbookDBEntities);
            //bankBookViewSource.Source = bankBookQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
        }

        private void ShowBankbook()
        {
            dataGridBankbook.ItemsSource = bankbookDBEntities.BankBook;

            if (dataGridBankbook.Items == null)
                return;

            // Select next item with no category
            foreach (object bankBookRowObject in dataGridBankbook.Items)
            {
                if (bankBookRowObject is BankBook)
                {
                    BankBook bankBookRow = (BankBook) bankBookRowObject;
                    if (bankBookRow.Category != null)
                        continue;

                    dataGridBankbook.SelectedItem = bankBookRow;

                    dataGridBankbook.ScrollIntoView(bankBookRow);

                    DataGridRow row =
                        (DataGridRow) dataGridBankbook.ItemContainerGenerator.ContainerFromItem(bankBookRow);

                    if (row != null)
                        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

                    break;
                }
            }

            SetFocusOnCategoryButton();
        }

        private void buttonRefreshBankbook_Click(object sender, RoutedEventArgs e)
        {
            ShowBankbook();
        }

        private void dataGridBankbook_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetFocusOnCategoryButton();
        }

        private void SetFocusOnCategoryButton()
        {

            if (dataGridBankbook.SelectedItem == null)
                return;

            BankBook selectedBankbook = (BankBook)dataGridBankbook.SelectedItem;

            if (selectedBankbook.Text == null)
                return;

            var allRowsWithSameText = bankbookDBEntities.BankBook.Where(b => b.Text == selectedBankbook.Text).ToList();

            var groupedByCategory = from bankbookRow in allRowsWithSameText
                                    group bankbookRow by bankbookRow.Category
                                        into groups
                                        select new { Category = groups.Key, Count = groups.Count() };

            var mostCommonCategory = groupedByCategory.OrderBy(o => o.Count).FirstOrDefault();

            string categoryTagText = null;
            if (mostCommonCategory != null)
                categoryTagText = mostCommonCategory.Category;

            foreach (Button button in categoryButtons)
            {
                if (categoryTagText != null && button.Tag != null && button.Tag.ToString() == categoryTagText)
                {
                    button.Focus();
                    FocusManager.SetFocusedElement(this, button);
                }
                else
                {
                    button.IsDefault = false;
                }
            }

        }

        private void button21_Click(object sender, RoutedEventArgs e)
        {
            DateTime fromDate = datePickerFrom.SelectedDate.Value;
            DateTime toDate = datePickerTo.SelectedDate.Value;

            var groupedByCategory = from bankbookRow in bankbookDBEntities.BankBook
                                    where bankbookRow.Date > fromDate && bankbookRow.Date < toDate
                                    group bankbookRow by bankbookRow.Category
                                    into groups
                                    select new Statistic
                                               {
                                                   Category = groups.Key,
                                                   Sum = groups.Sum(g => g.SEK)
                                               };
            dataGrid1.ItemsSource = groupedByCategory;
            dataGrid1.Columns.Clear();
            dataGrid1.Columns.Add(new DataGridTextColumn() {Binding = new Binding("Category"), Header = "Kategori"});
            dataGrid1.Columns.Add(new DataGridTextColumn() { Binding = new Binding("Sum"), Header = "Summa" });
        }

        public class Statistic
        {
            public string Category { get; set; }
            public double Sum { get; set;} 
        }

    }
}
